import { Card, Breadcrumb, Form, Button, Radio, Input, Upload, Space, Select, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import './index.scss'
// 导入富文本编辑器组件和样式
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

import { addArticleService, getArticleDetailService, updateArticleService } from '@/apis/article.js'

import { useState } from 'react'
import useChannel from '@/hooks/useChannel'
import { useEffect } from 'react'

const { Option } = Select

const Publish = () => {
  // 获取频道列表数据
  // 调用自定义hooks获取频道列表数据
  const { channels } = useChannel()

  // 提交表单
  const onFinish = async (formValues) => {
    // 校验封面类型type是否和实际的图片列表imageList数量是相等的
    if (imageList.length !== type) return message.warning('封面类型和图片数量不匹配')
    const reqData = {
      ...formValues,
      cover: {
        type, // 封面模式
        images: imageList.map((item) => {
          // 根据是否有response属性判断是否是上传成功的图片分别做不同处理
          if (item.response) {
            return item.response.data.url
          } else {
            // 编辑状态回显的图片列表
            return item.url
          }
        }) // 图片列表
      }
    }
    if (articleId) {
      // 编辑文章
      try {
        await updateArticleService({
          ...reqData,
          id: articleId
        })
        message.success('编辑文章成功')
        navigate('/article')
      } catch (error) {
        console.log(error)
        message.error('编辑文章失败')
      }
    } else {
      // 新增文章
      try {
        await addArticleService(reqData)
        message.success('发布文章成功')
        navigate('/article')
      } catch (error) {
        console.log(error)
        message.error('发布文章失败')
      }
    }
  }
  // 上传中、完成、失败都会调用这个函数
  const [imageList, setImageList] = useState([])
  const onUploadChange = (value) => {
    // console.log('上传文件中',value)
    setImageList(value.fileList)
  }
  // 路由跳转
  const navigate = useNavigate()

  // 切换封面类型
  const [type, setType] = useState(0)
  const onChangeType = (e) => {
    // console.log(e.target.value)
    setType(e.target.value)
  }

  // 获取文章详情
  // 获取查询字符串参数id
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')

  // 获取实例
  const [form] = Form.useForm()
  useEffect(() => {
    const getArticleDetail = async () => {
      try {
        const res = await getArticleDetailService(articleId)
        // 调用实例的方法回显数据
        form.setFieldsValue({
          ...res.data,
          type: res.data.cover.type
        })

        // 回显封面图片
        setType(res.data.cover.type)
        setImageList(
          res.data.cover.images.map((item) => ({
            url: item
          }))
        )
      } catch (error) {
        console.log(error)
      }
    }
    articleId && getArticleDetail()
  }, [articleId, form])
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb
            items={[
              { title: <Link to={'/'}>首页</Link> },
              { title: articleId ? '编辑文章' : '发布文章' }
            ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 0 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channels.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={onChangeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 
                listType: 决定选择文件框的外观样式
                showUploadList: 控制显示上传列表
            */}
            {type > 0 && (
              <Upload
                name="image"
                listType="picture-card"
                showUploadList
                action={'http://geek.itheima.net/v1_0/upload'}
                onChange={onUploadChange}
                maxCount={type}
                fileList={imageList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            {/* 富文本编辑器 */}
            <ReactQuill className="publish-quill" theme="snow" placeholder="请输入文章内容" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
